import { View, Text } from "@tarojs/components";
import React, { Component, useState } from "react";
import { useEffect } from "react";
import { AtTabs, AtTabsPane } from "taro-ui";
import CartFixedButton from "../../components/CartFixedButton";
import SmallGoodsCard from "../../components/SmallGoodsCard";
import { getAllCategory, getSecondaryCategory } from "../../api/category";
import { getGoodsList } from "../../api/index";
import "./index.scss";
import { getCurrentInstance } from "@tarojs/taro";

type GoodsCard = {
  attribute: string;
  categoryId: number;
  createTime: string;
  goodsId: number;
  goodsName: string;
  goodsPicture: string;
  isShow: number;
  price: number;
  quantity: number;
  stockId: number;
  updateTime: string;
};

type LeftItemType = {
  id: number;
  name: string;
};

export default () => {
  const [current, SetCurrent] = useState<number | string>(0);
  const [leftData, SetLeftData] = useState<LeftItemType[]>();
  const [rightData, SetRightData] = useState<GoodsCard[]>();
  const [shiftData, SetShiftData] = useState<GoodsCard[]>();
  useEffect(() => {
    const { router } = getCurrentInstance();
    const id = Number(router.params.id);
    if (id) {
      SetCurrent(id);
    }

    getSecondaryCategory().then(item => {
      const list = [];
      list.push({
        id: 0,
        name: "全部"
      });

      item.map(i => {
        list.push({
          id: i.categoryId,
          name: i.categoryName
        });
      });

      SetLeftData(list);
    });

    getGoodsList().then(item => {
      SetRightData(item);

      if (id != 0) {
        const data = item.filter(i => i.categoryId == id);
        SetShiftData(data);
      }
    });
  }, []);

  const changeRightData = index => {
    console.log(index);

    const data = rightData.filter(i => i.categoryId == index);
    SetShiftData(data);
  };

  return (
    <View className="ListWrapper">
      {/* 左边的列 */}
      <View className="LeftWrapper">
        {leftData &&
          leftData.map((item, index) => {
            return (
              <View
                key={item.id}
                className={["ListItem", current == item.id && "ListItemActive"]}
                onClick={() => {
                  SetCurrent(item.id);
                  changeRightData(item.id);
                }}
              >
                <View
                  className="SelectMark"
                  style={{ display: current == item.id ? "block" : "none" }}
                ></View>
                {item.name}
              </View>
            );
          })}
      </View>
      {/* 右侧的内容 */}
      <View className="RightWrapper">
        {current == 0
          ? rightData &&
            rightData.map(item => {
              return <SmallGoodsCard {...item} />;
            })
          : shiftData &&
            shiftData.map(item => {
              return <SmallGoodsCard {...item} />;
            })}
      </View>
      <CartFixedButton />
    </View>
  );
};
